/**
 *
 * app.js
 *
 * @create 2017-1-1
 * @author Young
 *
 * @update  Young 2017-01-05
 *
 */
var core = require('utils/core.js');

App({
  
    onShow: function () {
     // this.onLaunch();
    },
    onLaunch: function () {
      var openid=wx.getStorageSync('openid1')
      if(!openid){
        wx.login({
          success: res => {
              console.log(res)
              core.post('Getopenid',{code:res.code},function(res){
                  if(res.code==200){
                    var  openidinfo=JSON.parse(res.content);
                    console.log(openidinfo.openid)
                    wx.setStorageSync('openid1', openidinfo.openid)  
                  }
              })
          }
      })
      }
    var userinfo=wx.getStorageSync('userinfo')
    if(!userinfo){
      setTimeout(function(){
        wx.navigateTo({
          url:"/pages/authorize/login"
        })  
      },1000)   
    }
    return
      // 登录
      wx.login({
        success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            console.log(res)
        }
    })
    // 获取用户信息
    wx.getSetting({
        success: res => {
            if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                wx.getUserInfo({
                    success: res => {
                        // 可以将 res 发送给后台解码出 unionId
                        this.globalData.userInfo = res.userInfo

                        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                        // 所以此处加入 callback 以防止这种情况
                        if (this.userInfoReadyCallback) {
                            this.userInfoReadyCallback(res)
                        }
                    }
                })
            }
        }
    })

    return
      var $this = this; 
      wx.getSystemInfo({
        success: function (res) {
          var model = res.model;
          console.log(res)
          var iponeX = model.indexOf("iPhone X");
          if (iponeX == '0'){
            $this.setCache("isIpx", res.model);
          }else{
            $this.setCache("isIpx", '');
          }
        }
      }) 
      let that = this;
      wx.getSystemInfo({//  获取页面的有关信息
        success: function (res) {
          wx.setStorageSync('systemInfo', res)
          var ww = res.windowWidth;
          var hh = res.windowHeight;
          that.globalData.ww = ww;
          that.globalData.hh = hh;
        }
      }); 
    },
    /**
     * 小程序检查是否授权方法，写入当前页面路径和参数缓存
     * @date 2018-10-22
     * @author Vencenty
     */
    checkAuth: function () {
    
      const url = '/pages/message/auth/index'
      const currentPages = getCurrentPages()
      const currentPage = currentPages[currentPages.length - 1]
      const routeData = {
        'params': currentPage.options || null,
        'url': currentPage.route
      }

      // 处理扫码进来的商品信息
      if(routeData.params.hasOwnProperty('scene')) {
        const params = {}
        const scene = decodeURIComponent(routeData.params.scene)
        const paramsArr = scene.split('&').shift().split('=')
        params.id = paramsArr[1]
        routeData.params = params
      }
      
      this.setCache('routeData', routeData)


      const userinfo = this.getCache('userinfo')
      wx.getSetting({
        success: function (settings) {
          if (!settings.authSetting['scope.userInfo']) {
            wx.redirectTo({url: url})
          } else {
            if (!userinfo) {
              wx.redirectTo({ url: url })
            } else {
              core.get('member', {}, function (ret) {
                if (ret.error) {
                  wx.redirectTo({ url: url })
                }
              })
            }
          }
        }
      })
    },
    requirejs: function (jsname) {
        return require('utils/' + jsname + '.js');
    },
    test111:function(){
     console.log('44444444444444444444444444')
    },
    getConfig: function () {
        if (this.globalData.api !== null) {
            return {
                api: this.globalData.api,
                approot: this.globalData.approot,
                appid: this.globalData.appid
            };
        }
        var ext = wx.getExtConfigSync();
        
        this.globalData.api = ext.config.api;
        this.globalData.approot = ext.config.approot;
        this.globalData.appid = ext.config.appid;
        return ext.config;
    },
 
    getCache: function (key, defaultValue) {
        var time = (+new Date()) / 1000, data = '';
        time = parseInt(time);
        try {
            data = wx.getStorageSync(key + this.globalData.appid);
            if (data.expire > time || data.expire == 0) {
                data = data.value; 
            } else {
                data = '';
                this.removeCache(key);
            }
        } catch (e) {
            data = typeof (defaultValue) === 'undefined' ? '' : defaultValue;
        }
        data = data || '';
        return data;
    },

    setCache: function (key, value, expire) {
        var time = (+new Date()) / 1000, rt = true;
        var data = {
            expire: expire ? time + parseInt(expire) : 0,
            value: value
        };
        try {
            wx.setStorageSync(key + this.globalData.appid, data);
        } catch (e) {
            rt = false;
        }
        return rt;
    },
    
    removeCache: function (key) {
        var rt = true;
        try {
            wx.removeStorageSync(key + this.globalData.appid);
        } catch (e) {
            rt = false;
        }  
        return rt; 
    },
    close: function () {
      this.globalDataClose.flag = true;
      wx.reLaunch({
        url: '/pages/index/index',
      })
    },
    getSet: function () {
      var $this = this;
      var cacheset = $this.getCache("cacheset");
      if (cacheset == '') {
        // var sysset = $this.getCache("sysset");
        // if (sysset == '') {
        setTimeout(function () {
          var cacheset = $this.getCache("cacheset"); 
          core.get('cacheset', { version: cacheset.version }, function (result) {  
            if (result.update) {
              $this.setCache("cacheset", result.data);
            } 
            // $this.setCache("sysset", result.sysset, 7200);
          });
        }, 10);
      }
    },
    url: function (options) {
        options = options || {};
        var arg = {}, mid = '', merchid = '', user = this.getCache('usermid');
        mid = options.mid || '';
        merchid = options.merchid || '';

        for (let i in user) {
          if (typeof user[i] != 'undefined') {
            arg[i] = user[i]
          }
        }

        if (user != '') {
           
            if (user.mid == '' || typeof user.mid == 'undefined') {
                arg.mid = mid;
            }
            if (user.merchid == '' || typeof user.merchid == 'undefined') {
                arg.merchid = merchid;
            }
        } else {
            arg.mid = mid;
            arg.merchid = merchid;
        }
        this.setCache('usermid', arg);
    },
	/*再次发起授权*/
    impower: function(limit, msg, route) {
    	wx.getSetting({
    		success: function(res) {
    			var limits = res.authSetting['scope.' + limit];
    			if(!limits) {
    				wx.showModal({
    					title: '用户未授权',
    					content: '您点击了拒绝授权，暂时无法' + msg + '，点击去设置可重新获取授权喔~',
    					confirmText: '去设置',
    					success: function(res) {
    						if(res.confirm) {
    							wx.openSetting({
    								success: function(res) {}
    							})
    						}else{
    							if(route == 'route'){
    								wx.switchTab({
									    url: '/pages/index/index'
									})
    							}else if(route == 'details'){
    								//停留在当前页面
    							}else{
    								wx.navigateTo({
									    url: '/pages/index/index'
									})
    							}
    							
    						}
    					}
    				})
    			}
    		}
    	})
    },
    //未读消息
    getnoreadtotal:function(){
      var self=this
      return new Promise(function (resolve, reject) {
          core.post('Messages',{op:'noread'},function(res){
            console.log(res)
            if(res.code==1){
              self.globalData.noreadnum=res.data.total;//赋值用户信息     
                  console.log("myAsyncFunction done!");
                  resolve(self.globalData.noreadnum)     
            }
          })
      });
    },
    globalDataClose: {
      flag: false,
    },
   
    // 测试站
     globalData: {
       appid: "wxc8250fced9df71dc",
       api: "https://weiqing.parkic.com/app/index.php?i=3&c=entry&a=wxapp&m=wqq_game",
       approot: "https:/weiqing.parkic.com/addons/ewei_shopv2/",
       outurl: "https://out.parkic.com",
       userInfo: null,
       shareimg:'http://wqq103910.oss-cn-hangzhou.aliyuncs.com/images/3/2020/08/UVcKB60b9XbGBkxgocABT9Vxxoc26o.png',
       shareIndeximg:'http://wqq103910.oss-cn-hangzhou.aliyuncs.com/images/3/2020/09/m9eyn7f972w49h5Ca7W24H6ao2yO64.jpg',
       noreadnum:0
     }
    
    
})
  